﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Configuration;

/// <summary>
///WeiPage 的摘要说明
/// </summary>
public class WeiPage : System.Web.UI.Page
{
    public WeiPage()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    public string PostRequest(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);  //定义请求对象，并设置好请求URL地址
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();    //定义响应对象，request在调用GetResponse方法事执行请求了，而不是在HttpWebRequest.Create的时候执行。
        Stream stream = response.GetResponseStream(); //定义一个流对象，来获取响应流
        StreamReader sr = new StreamReader(stream);  //定义一个流读取对象，读取响应流
        string responseHTML = sr.ReadToEnd();
        return responseHTML;
    }

    public void AlertMessage(string message)
    {
        Page.RegisterStartupScript("AlertMessage", "<script language='javascript'>alert(\"" + message.Replace("'", "′") + "\");</script>");
    }



    /// <summary>
    /// 再客户端显示一条信息，然后转到一个页面
    /// </summary>
    /// <param name="message">显示的信息</param>
    /// <param name="url">转到页面路径</param>
    protected void AlertRedirect(string message, string url)
    {
        Page.RegisterStartupScript("AlertRedirect", "<script language='javascript'>alert(\"" + message.Replace("'", "′") + "\");window.navigate('" + url + "');</script>");
    }
    /// <summary>
    /// 再客户端显示一条信息，然后关闭页面
    /// </summary>
    /// <param name="message"></param>
    protected void AlertClose(string message)
    {
        Page.RegisterStartupScript("AlertClose", "<script language='javascript'>alert(\"" + message.Replace("'", "′") + "\");window.close();</script>");
    }

    /// <summary>
    /// 关闭窗口
    /// </summary>
    protected void CloseWindow()
    {
        Page.RegisterStartupScript("CloseWindow", "<script language='javascript'>window.close();</script>");
    }


    /// <summary>
    /// 在客户端显示一条信息，然后返回上一个页面
    /// </summary>
    /// <param name="message"></param>
    protected void AlertReflashFrame(string message, string frame)
    {
        Page.RegisterStartupScript("AlertReflashFrame_" + frame, "<script language='javascript'>alert('"
            + message.Replace("'", "′") + "');window.parent.frames['" + frame + "'].location.reload();</script>");
    }

    /// <summary>
    ///  在客户端显示一条信息，然后把页面刷新一遍
    /// </summary>
    /// <param name="message"></param>
    public void AlertReLoad(string message)
    {
        Page.RegisterStartupScript("AlertReLoad", "<script language='javascript'>alert('"
            + message.Replace("'", "′") + "');window.location.href=window.location.href;</script>");
    }


    /// <summary>
    /// 获取站点根路径
    /// </summary>
    /// <returns></returns>
    protected string GetSitePath()
    {
        string root = Page.Request.ApplicationPath;
        if (root == "/") return root;
        else return root + "/";
    }

    protected void ReturnMessage(string msg)
    {

        //Exception ex = Server.GetLastError();

        //string root = this.GetSitePath();
        //string css = "<link rel='stylesheet' href='" + root + "Skin/Main.css'/>";
        Response.Clear();
        //Response.Write(css);
        //Response.Write( "<br><br><h3><font color='red'>系统运行发生错误!请联系管理员!</font></h3><br>错误信息:" );
        //Response.Write( "<hr size='1' color='red'><b>" + msg + "</b><hr size='1' color='red'>" );
        //Response.Write(  ex.StackTrace );

        //出错信息提示样式
        string strHtml = "<body  bgcolor='#CCCCCC'><br><br><br><br><br><br>";
        strHtml += "<div align='center'>";
        strHtml += "  <table width='80%' border='1' cellspacing='0' bordercolorlight='000000' bordercolordark='FFFFFF' bgcolor='E0E0E0'>";
        strHtml += "    <tr>";
        strHtml += "      <td><table border='0' bgcolor='#0066CC' cellspacing='0' cellpadding='2'  height='35'  width='100%'>";
        strHtml += "          <tr>";
        strHtml += "            <td align='center'><font color='FFFFFF' size='3'><b>System messages</b></font></td>";
        strHtml += "          </tr>";
        strHtml += "          </table>";
        strHtml += "          <table border='0' width='100%' cellpadding='4'>";
        strHtml += "            <tr>";
        //strHtml += "              <td width='59' align='center' valign='top'><img src='" + root + "images/28.png'/></td>";
        strHtml += "              <td colspan='2' align='center'><font size='2'><b>" + msg + "</b></font></td>";
        strHtml += "            </tr>";
        strHtml += "            <tr>";
        strHtml += "              <td colspan='2' align='center' valign='top'><input type='button' name='ok' class='formButton' value='　Return　' onclick='javascript:history.back()' />";
        strHtml += "              </td>";
        strHtml += "            </tr>";
        strHtml += "        </table></td>";
        strHtml += "    </tr>";
        strHtml += "  </table>";
        strHtml += "</div></body>";

        Response.Write(strHtml);
        Response.End();
    }



    public string GetAppid()
    {
        //return "wx9283e34e38cd93ee";
        //return "wx8ecea9aaa3d6162b";
      string id=  ConfigurationManager.AppSettings["appid"].ToString();
      return id;
      
    }

    public string GetSecret()
    {
        //return "4c3fd2fe83b8af3d8321c48774598ed1";
        //return "6766f98e57832e81f1dc00cbefb15221";
        string s= ConfigurationManager.AppSettings["appsecret"].ToString();
        return s;
    }

    public string Token()
    {
        string Access_token = "";
        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + GetAppid() + "&secret=" + GetSecret();
        try
        {
            string token = PostRequest(url);
            if (token.Contains("7200"))
            {
                string[] b = token.Split('\"');
                Access_token = b[3];
            }
        }
        catch (Exception)
        {
            Access_token = "";
        }
        return Access_token;
    }


    public static string HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding)
    {
        if (string.IsNullOrEmpty(postUrl))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException :  postUrl IsNullOrEmpty");
        }

        if (string.IsNullOrEmpty(postXml))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty");
        }

        var request = (HttpWebRequest)WebRequest.Create(postUrl);
        byte[] byteArray = encoding.GetBytes(postXml);
        request.ContentLength = byteArray.Length;
        request.Method = "post";
        request.ContentType = "text/xml";

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(byteArray, 0, byteArray.Length);
        }

        using (var responseStream = request.GetResponse().GetResponseStream())
        {
            return new StreamReader(responseStream, encoding).ReadToEnd();
        }
    }
}